﻿using System;
using System.IO;
using System.Windows.Forms;
using Domino;

namespace T2ReportsAssistant
{
    partial class Assistant
    {
        private static NotesSession _session;
        private static NotesView _sourceView;
        private static NotesDateRange _dateRange;
        private static StreamWriter _resultsQueue;

        private static bool Initialize()
        {
            _session = new NotesSessionClass();

            Settings t = Settings.Instance;

            try
            {
                _session.Initialize(Settings.Instance.IdPassword);
            }
            catch
            {
                MessageBox.Show(
                    "Неправильно задан пароль пользователя для сессии Lotus Notes!\nДля настройки пароля используйте параметр /setup",
                    "T2 Reports Assistant: Ошибка инициализации программы",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            AddressBookContact[] contacts = NotesUtilities.SearchAddressBookContact(
                NotesUtilities.GetPublicAddressBook(_session),
                "Owner",
                _session.UserName,
                0
                );

            if (contacts.Length != 1)
            {
                MessageBox.Show(
                    "Невозможно определить пользователя для сессии Lotus Notes!",
                    "T2 Reports Assistant: Ошибка инициализации программы",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            AddressBookContact me = contacts[0];

            _sourceView = _session.GetDatabase(me["MailServer"], me["MailFile"], false).GetView(Settings.Instance.SourceView);

            if (_sourceView == null)
            {
                MessageBox.Show(
                    "Не найдена папка с отчетами в почтовой базе пользователя!\nПроверьте параметр SourceView в файле конфигурации.", "T2 Reports Assistant: Ошибка инициализации программы",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return false;
            }

            _dateRange = _session.CreateDateRange();
            _dateRange.StartDateTime = _session.CreateDateTime(Settings.Instance.StartDate.ToString());

            if (Settings.Instance.UseResultsFile)
            {
                try
                {
                    _resultsQueue = new StreamWriter(Settings.Instance.ResultsFile, true, System.Text.Encoding.Default);
                }
                catch
                {
                    MessageBox.Show(
                        "Невозможно создать/открыть для записи файл с результатами экспорта",
                        "T2 Reports Assistant: Ошибка инициализации программы",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return false;
                }
            }

            return true;
        }

        private static int ExtractAllAttachments(NotesDocument document)
        {
            int cnt = 0;

            string[] attachmentNames = NotesUtilities.GetAttachmentNames(document);

            if (attachmentNames.Length > 0)
            {
                object objDate = document.Created;

                DateTime created = ((objDate != null) && (objDate is DateTime)) ? (DateTime)objDate : DateTime.Now;
                string folderPath = Path.Combine(Settings.Instance.DestinationFolder, created.ToString("yyyyMMdd"));

                Directory.CreateDirectory(folderPath);

                string fileName;
                foreach (string attachment in attachmentNames)
                {
                    fileName = Path.Combine(folderPath, attachment);
                    document.GetAttachment(attachment).ExtractFile(fileName);

                    if (Settings.Instance.UseResultsFile)
                        _resultsQueue.WriteLine(fileName);
                    cnt++;
                }
            }

            return cnt;
        }

        private static int ExtractAllReports()
        {
            int reportsCount = 0;

            DateTime startDate = DateTime.Now;
            _dateRange.EndDateTime = _session.CreateDateTime(startDate.ToString());

            NotesDocumentCollection documents = _sourceView.GetAllDocumentsByKey(_dateRange, false);

            for (int docCount = 1; docCount <= documents.Count; docCount++)
            {
                NotesDocument document = documents.GetNthDocument(docCount);

                #region Extract the report as an attachment, if successful then proceed to the next document.

                int cnt = ExtractAllAttachments(document);
                reportsCount += cnt;
                if (cnt > 0)
                    continue;
                #endregion

                #region Extract the report from the link.

                NotesRichTextItem rti = document.GetFirstItem("Body") as NotesRichTextItem;

                if (rti == null) continue;

                NotesRichTextNavigator rtiNavigator = rti.CreateNavigator();
                if ((rtiNavigator != null) && rtiNavigator.FindFirstElement(RT_ELEM.RTELEM_TYPE_DOCLINK))
                {
                    NotesRichTextDoclink link = rtiNavigator.GetElement() as NotesRichTextDoclink;

                    if (link == null) continue;

                    NotesDbDirectory directory = _session.GetDbDirectory(link.ServerHint);
                    NotesDatabase linkDB = directory.OpenDatabaseByReplicaID(link.DBReplicaID);
                    if ((linkDB != null) && linkDB.IsOpen)
                    {
                        NotesDocument linkDoc = linkDB.GetDocumentByUNID(link.DocUNID);

                        if (linkDoc == null) continue;

                        string fileServer = NotesUtilities.GetItemValueText(linkDoc, "File_Server");
                        string filePath = NotesUtilities.GetItemValueText(linkDoc, "File_Filepath");
                        string fileUNID = NotesUtilities.GetItemValueText(linkDoc, "File_UNID");

                        if (String.IsNullOrEmpty(fileServer) || String.IsNullOrEmpty(filePath) || String.IsNullOrEmpty(fileUNID))
                            continue;

                        NotesDatabase fileDB = null;
                        try
                        {
                            fileDB = _session.GetDatabase(fileServer, filePath, false);
                        }
                        catch
                        {
                        }

                        if (fileDB == null) continue;

                        NotesDocument fileDocument = fileDB.GetDocumentByUNID(fileUNID);

                        if (fileDocument == null) continue;

                        reportsCount += ExtractAllAttachments(fileDocument);
                    }
                }
                #endregion
            }

            Settings.Instance.StartDate = startDate;

            if (Settings.Instance.UseResultsFile)
                _resultsQueue.Close();

            return reportsCount;
        }
    }
}
